package middleware

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

// 定义用户名和密码
var users = map[string]string{
	"ks":    "BdWQ7RqxFhHgYqW9",
	"admin": "Manager@2020",
}

// BaseAuth 验证中间件
func BaseAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取请求中的Authorization头
		user, password, hasAuth := c.Request.BasicAuth()
		if hasAuth {
			// 检查用户名和密码是否匹配
			if pass, ok := users[user]; ok && pass == password {
				// 如果匹配，继续执行请求
				c.Next()
				return
			}
		}
		// 如果认证失败，返回401状态码
		c.Header("WWW-Authenticate", `Basic realm="Restricted"`)
		c.AbortWithStatus(http.StatusUnauthorized)
	}
}
